# -*- coding: utf-8 -*-
"""
---------------------------------------
@File    ：ip_check.py
@Author  ：liyunhui
@Date    ：2024/9/14 下午3:59 
@explain : 文件说明
---------------------------------------
"""
# todo: 检测各个拨号服务器生成的代理，并检测代理是否有效, 通过测试发现该服务无法测试代理是否有效，
#  原因：境外IP代理必须要在境外服务器测试
import json
import tornado
import traceback
from datetime import datetime
from methods.custom_log import create_logging
from methods.proxy_check import IpStatusCheck
from tornado_swagger.model import register_swagger_model


@register_swagger_model
class IpCheckModel:
    """
    ---
    type: object
    description: GET model for IP check
    properties:
        status:
            type: string
            description: 请求状态
            example: success
        message:
            type: string
            description: 返回的消息
            example: 代理检测启动成功！
    """


class IpCheckHandler(tornado.web.RequestHandler):
    def __init__(self, *args, **kwargs):
        super(IpCheckHandler, self).__init__(*args, **kwargs)
        self.logging = create_logging("ip_check")

    def get(self):
        """
        启动 IP 代理状态检查
        ---
        tags:
          - IP 检测
        summary: 启动 IP 代理状态检查任务
        description: 该接口启动 IP 代理检测服务，检查代理的状态，并记录相关日志。注意该接口暂时不
        produces:
          - application/json
        responses:
          200:
            description: 成功启动代理检测服务
            schema:
              type: object
              properties:
                status:
                  type: string
                  description: 请求状态
                  example: success
                message:
                  type: string
                  description: 返回的消息
                  example: 代理检测启动成功！
          500:
            description: 服务器错误
            schema:
              type: object
              properties:
                status:
                  type: string
                  example: error
                message:
                  type: string
                  example: 代理检测启动失败！
        """
        try:
            local_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
            self.logging.info(f"代理检测服务启动----{local_time}")
            IpStatusCheck(logging=self.logging).handler()  # 启动 IP 状态检测逻辑
            self.write(json.dumps({'status': 'success', 'message': '代理检测启动成功！'}))
        except Exception as e:
            error_message = traceback.format_exc()  # 获取完整的异常堆栈信息
            self.set_status(500)
            self.write(json.dumps({'status': 'error', 'message': '代理检测启动失败！'}))
            self.logging.error(f"代理检测启动失败: {str(error_message)}")
